package com.example.shutdown_v1.repository;

import com.example.shutdown_v1.entity.SwitchStateRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface SwitchStateRecordRepository extends JpaRepository<SwitchStateRecord, Long> {
    
    /**
     * 查询指定传感器的最新状态记录
     */
    Optional<SwitchStateRecord> findFirstBySensorIdOrderByRecordTimeDesc(String sensorId);
    
    /**
     * 查询指定时间范围内的状态记录
     */
    List<SwitchStateRecord> findBySensorIdAndRecordTimeBetween(
            String sensorId, LocalDateTime startTime, LocalDateTime endTime);
    
    /**
     * 查询指定店铺在指定时间的所有开关状态
     */
    @Query("SELECT s FROM SwitchStateRecord s WHERE s.shopId = ?1 " +
           "AND s.recordTime = (SELECT MAX(sr.recordTime) FROM SwitchStateRecord sr " +
           "WHERE sr.sensorId = s.sensorId AND sr.recordTime <= ?2)")
    List<SwitchStateRecord> findLatestStatesByShopAndTime(Long shopId, LocalDateTime time);
    
    /**
     * 删除指定时间之前的状态记录
     * @param cutoffTime 截止时间
     * @return 删除的记录数
     */
    @Modifying
    @Query("DELETE FROM SwitchStateRecord s WHERE s.recordTime < :cutoffTime")
    int deleteByRecordTimeBefore(@Param("cutoffTime") LocalDateTime cutoffTime);
    
    /**
     * 统计指定时间之前的状态记录数量
     * @param cutoffTime 截止时间
     * @return 数据条数
     */
    long countByRecordTimeBefore(LocalDateTime cutoffTime);
}

